#!/bin/bash

# =============================================================================
# MemeBot Trading System - Ubuntu 24.04 部署脚本
# =============================================================================

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}


# 检查Ubuntu版本
check_ubuntu_version() {
    if ! grep -q "Ubuntu 24.04" /etc/os-release; then
        log_warning "此脚本专为Ubuntu 24.04设计，当前系统可能不兼容"
        read -p "是否继续？(y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# 主菜单
show_menu() {
    echo -e "\n${BLUE}=== MemeBot Trading System 部署脚本 ===${NC}"
    echo "1. 完整部署 (推荐新服务器)"
    echo "2. 系统环境安装"
    echo "3. 数据库配置"
    echo "4. 应用部署"
    echo "5. Nginx配置"
    echo "6. 服务配置"
    echo "7. 监控配置"
    echo "8. 安全加固"
    echo "9. 验证部署"
    echo "0. 退出"
    echo -e "${BLUE}=================================${NC}\n"
}

# 完整部署
full_deploy() {
    log_info "开始完整部署..."
    
    # 执行所有步骤
    ./scripts/01-system-setup.sh
    ./scripts/02-database-setup.sh
    ./scripts/03-app-deploy.sh
    ./scripts/04-nginx-config.sh
    ./scripts/05-service-setup.sh
    ./scripts/06-monitoring-setup.sh
    ./scripts/07-security-hardening.sh
    ./scripts/08-verify-deployment.sh
    
    log_success "完整部署完成！"
    log_info "请访问 http://$(curl -s ifconfig.me) 查看应用"
}

# 创建脚本目录
create_scripts_dir() {
    if [ ! -d "scripts" ]; then
        mkdir -p scripts
        log_info "创建scripts目录"
    fi
}

# 主函数
main() {
    
    check_ubuntu_version
    create_scripts_dir
    
    while true; do
        show_menu
        read -p "请选择操作 [0-9]: " choice
        
        case $choice in
            1)
                full_deploy
                ;;
            2)
                ./scripts/01-system-setup.sh
                ;;
            3)
                ./scripts/02-database-setup.sh
                ;;
            4)
                ./scripts/03-app-deploy.sh
                ;;
            5)
                ./scripts/04-nginx-config.sh
                ;;
            6)
                ./scripts/05-service-setup.sh
                ;;
            7)
                ./scripts/06-monitoring-setup.sh
                ;;
            8)
                ./scripts/07-security-hardening.sh
                ;;
            9)
                ./scripts/08-verify-deployment.sh
                ;;
            0)
                log_info "退出部署脚本"
                exit 0
                ;;
            *)
                log_error "无效选择，请重新输入"
                ;;
        esac
        
        echo
        read -p "按Enter键继续..."
    done
}

# 运行主函数
main "$@"
